package com.example.book.service.impl.admin;

import com.example.book.dto.AdminDTO;
import com.example.book.dto.UserPageDTO;
import com.example.book.entity.Admin;
import com.example.book.entity.Book;
import com.example.book.entity.User;
import com.example.book.mapper.AdminMapper;
import com.example.book.mapper.UserMapper;
import com.example.book.result.PageResult;
import com.example.book.service.impl.admin.AdminService;
import com.example.book.vo.UserVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountNotFoundException;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserMapper userMapper;
    //管理员登录
    @Override
    @Transactional
    public void login(AdminDTO adminDTO) throws AccountNotFoundException {
        String name = adminDTO.getName();
        String password = adminDTO.getPassword();
        Admin admin =  adminMapper.getAdminById(name);
        if(admin==null){
            //账号不存在的时候
            throw new AccountNotFoundException("账号不存在");
        }
        //md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(admin.getPassword())){
            //密码错误
            throw new AccountNotFoundException("密码错误");
        }
    }
    //查询用户信息
    @Override
    public PageResult UserPage(UserPageDTO userPageDTO) {
        PageHelper.startPage(userPageDTO.getPage(), userPageDTO.getPageSize());//获取页数和记录数
        Page<UserVO> page = userMapper.getUserPage(userPageDTO);//获取图书信息
        long total = page.getTotal();//获取总记录数
        List<UserVO> userVOS = page.getResult();//获取记录数的集合
        PageResult pageResult = new PageResult(total,userVOS);//将集合放入pageResult实体类中
        return pageResult;
    }
    //删除用户
    @Override
    public void deleteUserByName(List<String> name) {
        userMapper.deleteUser(name);
    }
}